package com.imooc.web.interceptor;

import java.time.Duration;
import java.time.LocalDateTime;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * @author JZH
 * 
 * 拦截器需要使用代码注册到拦截器栈中
 * 
 * 局限：拦截器无法获取请求方法的参数值
 *
 */
@Component
public class RequestLogInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("【拦截器】preHandle...");
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		System.out.println("【拦截器】请求方法："+handlerMethod.getBean().getClass().getName()+"-"+handlerMethod.getMethod().getName());
		LocalDateTime startTime = LocalDateTime.now();
		System.out.println("【拦截器】开始时间："+startTime);
		request.setAttribute("REQUEST_START_TIME", startTime);
		return true;
	}
	
	/**
	 * 只有正常完成才会被调用
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("【拦截器】postHandle...");
		LocalDateTime endTime = LocalDateTime.now();
		LocalDateTime startTime = (LocalDateTime)request.getAttribute("REQUEST_START_TIME");
		System.out.println("【拦截器】结束时间："+endTime);
		Duration duration = Duration.between(startTime, endTime);
		Long d = duration.toMillis();
		System.out.println("【拦截器】耗时："+d);
	}
	
	/**
	 * 无论请求是否正常执行，都会运行该方法，期间若抛异常，异常对象会作为参数传递进来
	 * 注意：如果设置了全局异常处理，则此处不会捕获异常
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("【拦截器】afterCompletion...");
	}
}
